const Router = require('koa-router');
const common = require('../libs/common');
const moment = require('moment');
const db = require('../libs/db');
const response = require('../libs/result');
let router = new Router();
const koa2Req = require('koa2-request')
const random = require('string-random')
const bankinfodict = require('../dict/bankinfo');
const eductiondict = require('../dict/eduction');
const loan_remarkdict = require('../dict/loan_remark');
const religiondict = require('../dict/religion');
const usertypedict = require('../dict/usertype');
const orderstatusdict = require('../dict/orderstatus');

/**
 * @api {post} /api/v1/order/getordercount  用户订单数量
 * @apiDescription 用户订单数量
 * @apiName getordercount
 * @apiParam (参数) {String} user_id   user_id
 * @apiSampleRequest /api/v1/order/getordercount
 * @apiGroup order
 * @apiVersion 1.0.0
 */
router.post('/getordercount', async ctx => {
  let { user_id } = ctx.request.body;

  //根据手机号获取借款人信息
  let loan_user = await ctx.db.query(`select b.* from auth_user a,loan_user b where a.phone_number=b.mobile and a.id=?`, [user_id]);

  if (loan_user.length == 0) {
    response(ctx, 200, { loaning: 0, loaned: 0 }, '用户订单数量')
    return;
  }
  loan_user = JSON.stringify(loan_user)
  loan_user = JSON.parse(loan_user)


  let userordering = await ctx.db.query(`
        SELECT a.id,b.images,b.name,a.loan_amount,a.loan_time,a.order_status FROM loan_order a,products_product b WHERE a.user_id=? and a.order_status<>200 and a.product_id=b.id `, [loan_user[0].id]);


  let userorders = await ctx.db.query(`
        SELECT b.images,b.name,a.loan_amount,a.loan_time,a.order_status FROM loan_order a,products_product b WHERE a.user_id=? and a.order_status=200 and a.product_id=b.id `, [loan_user[0].id]);
  response(ctx, 200, { loaning: userordering.length, loaned: userorders.length }, '用户订单数量')




})

/**
 * @api {post} /api/v1/order/getorderlist  用户订单列表
 * @apiDescription 用户订单列表
 * @apiName getorderlist
 * @apiParam  {String} user_id   user_id
 * @apiParam  {Number} order_status  0未完成订单 1已完成订单
 * @apiParam  {Number} page
 * @apiParam  {Number} pageSize
 * @apiParamExample {json} Request-Example:
 *     {
 *      "user_id":122794,
 *       "order_status":0,
 *       "page": 1,
 *       "pageSize": 10
 *     }
 * @apiSampleRequest /api/v1/order/getorderlist
 * @apiGroup order
 * @apiVersion 1.0.0
 */
router.post('/getorderlist', async ctx => {
  let input = ctx.request.body;
  //根据手机号获取借款人信息
  let loan_user = await ctx.db.query(`select b.* from auth_user a,loan_user b where a.phone_number=b.mobile and a.id=?`, [input.user_id]);

  if (loan_user.length == 0) {
    response(ctx, 200, [], '用户订单')
    return;
  }
  //let orderstatus = [{ name: "待补充材料", val: 80 }, { name: "审核中", val: 90 }, { name: "审批资料重填", val: 99 }, { name: "审批通过", val: 100 }, { name: "审批不通过", val: 110 }, { name: "贷款取消", val: 161 }, { name: "放款失败", val: 169 }, { name: "贷款取消", val: 161 }, { name: "放款成功", val: 170 }, { name: "还款期", val: 175 }, { name: "逾期", val: 180 }, { name: "宽限期", val: 185 }, { name: "贷款结清", val: 200 }]
  loan_user = JSON.stringify(loan_user)
  loan_user = JSON.parse(loan_user)
  let userorders;
  if (input.order_status == 0) {
    userorders = await ctx.db.query(`
        SELECT a.id,b.images,b.name,a.loan_amount,a.loan_time,a.order_status FROM loan_order a,products_product b WHERE a.user_id=? and a.order_status<>200 and a.product_id=b.id ORDER BY a.created_time DESC LIMIT ?,?`, [loan_user[0].id, (input.page - 1) * input.pageSize, parseInt(input.pageSize)]);

  } else if (input.order_status == 1) {
    userorders = await ctx.db.query(`
        SELECT a.id,b.images,b.name,a.loan_amount,a.loan_time,a.order_status FROM loan_order a,products_product b WHERE a.user_id=? and a.order_status=200 and a.product_id=b.id ORDER BY a.created_time DESC LIMIT ?,?`, [loan_user[0].id, (input.page - 1) * input.pageSize, input.pageSize]);
  }
  if (userorders.length > 0) {
    userorders.map(function (item, index, input) {
      item.images = ctx.config.productimgurl + item.images;
      orderstatusdict.map(function (ods, index, input) {
        if (ods.val == item.order_status) {
          item.order_status_msg = ods.name
          item.bgcolor=ods.bgcolor;
          item.strcolor=ods.strcolor;
        }
      });
    })
  }
  response(ctx, 200, userorders, '用户订单列表');
})



/**
 * @api {post} /api/v1/order/getorderdetail  用户订单详情
 * @apiDescription 用户订单详情
 * @apiName getorderdetail
 * @apiParam (参数) {String} user_id   用户id
 * @apiParam (参数) {String} orderid   订单id
 * @apiSampleRequest /api/v1/order/getorderdetail
 * @apiGroup order
 * @apiVersion 1.0.0
 */
router.post('/getorderdetail', async ctx => {
  let { user_id, orderid } = ctx.request.body;
  let headers= ctx.request.headers;
  console.log(headers);
  let currentlng=headers.lang;
  //印尼语
  let orderstatus_ind = [{ name: "Untuk ditambah", val: 80 }, { name: "Sedang ditinjau", val: 90 }, { name: "Dokumen persetujuan dikembalikan", val: 99 }, { name: "Disetujui", val: 100 }, { name: "Persetujuan gagal", val: 110 }, { name: "Pembatalan pinjaman", val: 161 }, { name: "Pinjaman gagal", val: 169 }, { name: "Meminjamkan kesuksesan", val: 170 }, { name: "Periode pembayaran", val: 175 }, { name: "Terlambat", val: 180 }, { name: "Masa tenggang", val: 185 }, { name: "Penyelesaian pinjaman", val: 200 }]

  //英文
  let orderstatus_en = [{ name: "Materials to be supplemented", val: 80 }, { name: "In audit", val: 90 }, { name: "Re filling of approval data", val: 99 }, { name: "Approval and approval", val: 100 }, { name: "Approval failed", val: 110 }, { name: "Cancellation of loan", val: 161 }, { name: "Loan failure", val: 169 },  { name: "Loan success", val: 170 }, { name: "Repayment period", val: 175 }, { name: "Be overdue", val: 180 }, { name: "Grace period", val: 185 }, { name: "Loan settlement", val: 200 }]

  //根据手机号获取借款人信息
  let loan_user = await ctx.db.query(`select b.* from auth_user a,loan_user b where a.phone_number=b.mobile and a.id=?`, [user_id]);
  loan_user = JSON.stringify(loan_user)
  loan_user = JSON.parse(loan_user)
  let userorders = await ctx.db.query(`
        SELECT b.api_contract,a.id,b.images,b.name,a.loan_amount,a.loan_time,a.order_status,a.loan_amount,a.actual_amount,a.repay_amount,b.rate as interest_rate,b.api_contract,
        a.interest_amount,a.admin_amount,a.loan_term,a.order_no,c.bank_name,c.bank_account,c.bank_user_name,a.loan_time FROM loan_order a,products_product b,loan_bank_info c WHERE a.user_id=? and a.id=?  and a.product_id=b.id and a.bank_card_id=c.id   and a.user_id=c.owner_id`, [loan_user[0].id, orderid]);
  if (userorders.length > 0) {
    userorders.map(function (item, index, input) {
      item.images = ctx.config.productimgurl + item.images;
      orderstatusdict.map(function (ods, index, input) {
        if (ods.val == item.order_status) {
          if(currentlng=="en-US"){
            item.order_status_msg = orderstatus_en[index].name
          }
          if(currentlng=="zh-CN"){
            item.order_status_msg = ods.name
          }
          if(currentlng=="in-ID"){
            item.order_status_msg = orderstatus_ind[index].name
          }
          item.bgcolor=ods.bgcolord;
          item.strcolor=ods.strcolor;
        }
      });

    })
  }
  ctx.body = common.handleResulte(200, userorders[0]);
})


/**
 * @api {post} /api/v1/order/loanpymentlink  获取还款h5链接
 * @apiDescription 获取还款h5链接
 * @apiName loanpymentlink
 * @apiParam (参数) {String} user_id   用户id
 * @apiParam (参数) {String} orderid   订单id
 * @apiSampleRequest /api/v1/order/loanpymentlink 
 * @apiGroup order
 * @apiVersion 1.0.0
 */
router.post('/loanpymentlink', async ctx => {
  try {
    let { user_id, orderid } = ctx.request.body;
  let loan_user = await ctx.db.query(`select b.* from auth_user a,loan_user b where a.phone_number=b.mobile and a.id=?`, [user_id]);
  loan_user = JSON.stringify(loan_user)
  loan_user = JSON.parse(loan_user)
  let userorder = await ctx.db.query(`
      SELECT a.id,,a.order_no,a.third_order_no,c.bank_name,b.domain,b.appid,b.key,b.id as productid FROM loan_order a,products_product b,loan_bank_info c,loan_user d WHERE a.user_id=? and a.id=? and a.user_id=d.  and a.product_id=b.id and a.bank_card_id=c.id   and a.user_id=c.owner_id`, [loan_user[0].id, orderid]);
  userorder = JSON.stringify(userorder)
  userorder = JSON.parse(userorder)
  let jsondata = {
    appId: userorder.appid,
    loanId: userorder.third_order_no,
    nonce: random(32),
    productId: userorder.productid,
  };
  let signstr = common.signjsapiv2(jsondata, userorder.key)

  //jsondata.sign = signstr;
  var options = {
    method: 'post',
    url: userorder.domain,
    json: signstr,
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  }
  let reslink = await koa2Req(options);
  console.log(reslink);
  reslink = JSON.parse(res)
 
  response(ctx, 200, reslink.data)
  } catch (error) {
    console.log(error)
    response(ctx, 200, '')
  }
})

/**
 * @api {post} /api/v1/order/buildorder  生成订单
 * @apiDescription 生成订单
 * @apiName buildorder
 * @apiParam (参数) {Array} items   额度数组
 * @apiParam (参数) {String} user_id   用户id
 * @apiParam (参数) {String} bank_id   银行id
 * @apiSampleRequest /api/v1/order/buildorder
 * @apiGroup order
 * @apiVersion 2.0.0
 */
router.post('/buildorder', async ctx => {
  let { items, user_id, bank_id } = ctx.request.body;
  console.log(items);
  console.log(user_id);
  console.log(bank_id);
  try {
    let order_nos = [];
    let loan_user = (await db.querysql(ctx, `SELECT a.id AS userid,c.channel  FROM loan_user a , auth_user c WHERE a.mobile = c.phone_number  AND c.id=${user_id}`))[0];
    console.log(items.length);
    for (let index = 0; index < items.length; index++) {
      let item = items[index];
      console.log(item);
      let products_product = await db.queryById(ctx, 'products_product', item.id);
      let datenow = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
      let prds= await getmoney(products_product,item,ctx);
      console.log('获取管理费：'+ JSON.stringify(prds));
      let basic = {
        created_time: datenow,
        updated_time: datenow,
        is_active: 1,
        order_status: 90,
        loan_time: datenow,
        term_type: 0,
        term_unit: 1,// 1   天     2   月
        amount_type: 0,
        repay_method: 0,// 还款方式   0 银行    1 便利店
        pull_status: 0,
        bank_card_id: bank_id,
        customer_id: products_product.customer_id,
        user_id: loan_user.userid,
        product_id: products_product.id,
        //third_order_no:
        error_msg: null,
        channel: loan_user.channel,
        push_date: null,
        pid: 0,
        admin_amount: prds.admin_amount, //管理费
        interest_amount: prds.lmount, //利息
        interest_rate: prds.rate*10000,//利率
        //interest_rate: 1,
        actual_amount: prds.actual_amount,//实际到账金额
        repay_amount: prds.repay_total_amount// 还款金额
      };
      basic.order_no = moment(new Date()).format('YYYYMMDD') + common.randomnum(10);
      order_nos.push(basic.order_no);
      basic.loan_amount = item.loan_amount;
      basic.loan_term = item.period;
      basic.third_order_no = common.randomnum(10);
      // results.push(basic);
      await ctx.db.query(`INSERT INTO loan_order (created_time,updated_time,is_active, order_status, loan_time, term_type,term_unit, amount_type,repay_method,
      pull_status,bank_card_id,customer_id,user_id,product_id,error_msg,channel,push_date,pid,order_no,loan_amount,loan_term,third_order_no,admin_amount,interest_amount,interest_rate,actual_amount,repay_amount) 
      VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, [basic.created_time, basic.updated_time, basic.is_active, basic.order_status, basic.loan_time,
      basic.term_type, basic.term_unit, basic.amount_type, basic.repay_method, basic.pull_status, basic.bank_card_id, basic.customer_id, basic.user_id,
      basic.product_id, basic.error_msg, basic.channel, basic.push_date, basic.pid, basic.order_no, basic.loan_amount, basic.loan_term, basic.third_order_no,basic.admin_amount,basic.interest_amount,basic.interest_rate,basic.actual_amount,basic.repay_amount]);
    }
    sendorder(ctx, order_nos);
    //更新活体分数
    if (loan_user) {
      try {
          let jdata = {
              loan_user_id: loan_user.userid
          };
          var options = {
              method: 'post',
              url: ctx.config.faceapi,
              json: jdata,
              headers: {
                  'Content-Type': 'application/json',
                  'Accept': 'application/json'
              }
          }
          let res = await koa2Req(options);
          console.log("获取活体检测分数:" + res);
          if (res.code == 0) {
              let strsql = `Update loan_user_info set updated_time= '${datenow}',similarityValue='${res.code}' where id = ${loan_user.info_id}`;
              await ctx.db.query(strsql);
          }
      } catch (error) {
          console.log(error);
      }
  }
    response(ctx, 200, '', '提交订单成功');
  } catch (error) {
    console.log(error)
    response(ctx, 201, '', '提交订单失败');
  }
})

async function getmoney(products_product, a,ctx) {
  console.log(JSON.stringify(products_product))
 //扩展额度
 let  plqstr=`SELECT loan_amount,period,admin_amount,rate from product_loan_quota  WHERE product_id=${a.id} and loan_amount=${a.loan_amount} and period=${a.period} order by loan_amount`
 let parli3 = await ctx.db.query(plqstr);
 let quota={};

  if (products_product) {

    if(products_product.api_amount==1){
     if(!parli3){
      quota=parli3[0];
     }else{
      quota=products_product;
     }
      
  }
  if(products_product.api_amount==0){
    
    quota=products_product;
  
  }
console.log(quota);
    let res = {
      rate: quota.rate
    };
    /** 管理费计算方式    (0, '本金*天数*管理利率'), (1, '本金*管理利率'), (2, '固定金额') */
    let admin_mount = 0;
    switch (products_product.admin_amount_type) {
      case 0:
        admin_mount = common.mul(common.mul(a.loan_amount, quota.admin_amount), a.period);
        break;
      case 1:
        admin_mount = common.mul(a.loan_amount, quota.admin_amount);
        break;
      case 2:
        admin_mount = quota.admin_amount;
        break;
      default:
        //admin_mount = products_product.admin_amount;
        break;
    }
    res.admin_amount = admin_mount;
    /** 计算利息 loan_rate利率*/
    let lmount = common.mul(common.mul(a.loan_amount, quota.rate), a.period);
    res.lmount = lmount;
    /** 贷款模式      (0, _('预扣利息模式')), (1, _('非预扣利息模式')) */
    switch (products_product.loan_type) {
      // 计算实际到账金额和总还款额
      case 0:
        // 实际到账金额 = 额度-利息-管理费
        res.actual_amount = common.sub(common.sub(a.loan_amount, lmount), admin_mount);
        // 总还款额=本金
        res.repay_total_amount = a.loan_amount;
        break;
      case 1:
        // 实际到账金额 = 额度-管理费
        res.actual_amount = common.sub(a.loan_amount, admin_mount);
        // 总还款额=本金+利息
        res.repay_total_amount = common.add(a.loan_amount, lmount);
        break;
      default:
        break;
    }
    return res;
  }else{
    console.log('产品利率或管理费未配置');
  }
}

/** 订单推送客户 */
async function sendorder(ctx, order_nos) {
  for (let index = 0; index < order_nos.length; index++) {
    const id = order_nos[index];
    await getpars(ctx, id);
  }
}
router.post('/testorder', async ctx => {
  let { id } = ctx.request.body;
  await getpars(ctx, id);
})
/** 获取参数 */
async function getpars(ctx, id) {
  let res = {
    appId: '',
    bankCardDO: {},
    faceVerifyEntity: {},
    applyDTO: {},
    harvesterDOS: {},
    recordContacts: {},
    recordEmployment: {},
    recordFiles: {},
    recordPersonalInfo: {},
    deviceInfo: {},
  };
  let loan_order = await db.queryone(ctx, 'loan_order', `bank_card_id,customer_id,product_id,user_id,channel`, { order_no: id });
  if (loan_order) {
    // 用户收款银行卡信息
    let bankCardDOData = await db.queryone(ctx, 'loan_bank_info', 'bank_account as bankAccount,opening_bank as branchName,bank_user_name as userName,bank_name as bankName,bank_code as bankCode', { id: loan_order.bank_card_id });
    if (bankCardDOData) {
      //res.bankCardDO= JSON.stringify(bankCardDOData);
      res.bankCardDO=common.objKeySort(bankCardDOData);
      console.log(res.bankCardDO)
      console.log('获取用户收款银行卡信息成功');
    } else {
      console.log('获取用户收款银行卡信息失败');
    }
    // 人脸识别信息
    let faceData = await db.querysql(ctx, `SELECT b.best_path AS bestPath,b.ktp_path AS ktpPath,b.env_path AS envPath,b.similarityValue AS similarityValue FROM loan_user a,loan_user_info b WHERE a.info_id= b.id AND a.id=${loan_order.user_id}`);
    let faceVerifyEntity;
    if (faceData && faceData.length > 0) {
      faceVerifyEntity = faceData[0];
      faceVerifyEntity.bestPath = ctx.config.fileurl + faceVerifyEntity.bestPath;
      faceVerifyEntity.ktpPath = ctx.config.fileurl + faceVerifyEntity.ktpPath;
      faceVerifyEntity.envPath = ctx.config.fileurl + faceVerifyEntity.envPath;
      res.faceVerifyEntity = common.objKeySort(faceVerifyEntity);
      console.log(res.faceVerifyEntity)
      console.log('获取人脸识别信息成功');
    } else {
      console.log('获取人脸识别信息失败');
    }
    // 用户及产品信息
    let applyDTOdata = await db.querysql(ctx, `SELECT a.product_id AS productId ,a.loan_amount AS amount,a.loan_term AS period,a.interest_rate AS loanInterestRate,a.admin_amount AS loanHandleFee,b.mobile,b.loan_remark,b.id_card_number AS credentialNo FROM loan_order a,loan_user b WHERE a.user_id=b.id AND a.order_no=${id}`);
    if (applyDTOdata && applyDTOdata.length > 0) {
      let applyDTO = applyDTOdata[0];
      applyDTO.credentialType = 'KTP';
      applyDTO.unit = 'DAYS';
      switch (applyDTO.loan_remark) {
        case 1:
          applyDTO.purpose = 'Konsumsi harian';
          break;
        case 2:
          applyDTO.purpose = 'Bepergian';
          break;
        case 3:
          applyDTO.purpose = 'Dekorasi';
          break;
        case 4:
          applyDTO.purpose = 'Pendidikan';
          break;
        case 5:
          applyDTO.purpose = 'Medis';
          break;
        case 6:
          applyDTO.purpose = 'Perputaran modal';
          break;
        default:
          break;
      }
      delete applyDTO.loan_remark;
      res.applyDTO =  common.objKeySort(applyDTO);
      console.log(res.applyDTO)
      console.log('获取用户及产品信息成功');
    } else {
      console.log('获取用户及产品信息失败');
    }
    // 用户设备、通讯录相关信息
    let loan_user = (await db.querysql(ctx, `SELECT b.mobile FROM loan_order AS a, loan_user AS b  WHERE  a.user_id= b.id AND a.order_no=${id}`))[0];
    let device_infoData = await db.querysql(ctx, `SELECT a.* FROM device_info AS a,auth_user AS b WHERE a.user_id = b.id AND b.phone_number='${loan_user.mobile}'`);
    let device_info;
    if (device_infoData && device_infoData.length > 0) {
      device_info = device_infoData[0];
      let harvesterDOS = [
        {
          androidId: device_info.android_id,
          body: device_info.contacts,
          type: 'CONTACTS'
          
        },
        {
          androidId: device_info.android_id,
          body: device_info.device,
          type: 'DEVICE'
         
        }
      ];
      res.harvesterDOS =  harvesterDOS;
      console.log(res.harvesterDOS)
      console.log('获取用户设备、通讯录相关信息成功');
    } else {
      console.log('获取用户设备、通讯录相关信息失败');
    }
    // 用户联系人的手机号码
    let recordContacts = await db.querysql(ctx, `SELECT mobile,'name',relation FROM loan_contacts WHERE owner_id= ${loan_order.user_id}`);
    if (recordContacts) {
      res.recordContacts =  recordContacts;
      console.log(res.harvesterDOS)
      console.log('获取用户联系人的手机号码成功');
    } else {
      console.log('获取用户联系人的手机号码失败');
    }
    // 用户工作信息
    let recordEmployment = await db.querysql(ctx, `SELECT a.company_name AS companyName,a.company_address AS companyAddress,a.company_phone AS companyPhone,a.company_province AS companyProvince,
    a.company_city AS companyCity,a.company_district AS companyDistrict,a.company_area AS companyArea,a.profession,a.salary
    FROM loan_user_info a, loan_user b WHERE a.id= b.info_id AND b.id=${loan_order.user_id}`);
    if (recordEmployment && recordEmployment.length > 0) {
      res.recordEmployment =  common.objKeySort(recordEmployment[0]);
      console.log(res.recordEmployment)
      console.log('获取用户工作信息成功');
    } else {
      console.log('获取用户工作信息失败');
    }
    // 用户上传照片信息 
    if (faceVerifyEntity) {
      let recordFiles = [
        {
          fileKind: 'IMAGE',
          fileType: 'KTP_PHOTO',
          path: faceVerifyEntity.ktpPath
        },
        {
          fileKind: 'IMAGE',
          fileType: 'EMPLOYMENT_P HOTO',
          path: faceVerifyEntity.envPath
        }
      ];
      res.recordFiles =  recordFiles;
      console.log(res.recordFiles)
      console.log('获取用户上传照片信息成功');
    } else {
      console.log('获取用户上传照片信息失败');
    }
    // 用户个人信息
    let cupms= await db.querysql(ctx,'select `key` from customers_customparams where is_active=1');
    let cupmstr='';
    let cki=1;
    cupms.map(function (item, index, input) {
     
      if(cki==cupms.length){
        cupmstr+='a.'+item.key;
      }else{
        cupmstr+='a.'+item.key+',';
      }
      cki++;
    });

    // let recordPersonalInfoData = await db.querysql(ctx, `SELECT a.full_name,b.religion,a.birthday,b.id_card_number AS credentialNo,'KTP' AS credentialType,
    // a.province,a.city,a.district,a.area,a.address,b.education AS lastEducation,a.gender,a.marital_status,
    // a.children_number,a.residence_duration AS residenceDuration,a.workTime,a.bankPhone,a.whatsApp,a.email
    // FROM loan_user_info a, loan_user b WHERE a.id= b.info_id AND b.id=${loan_order.user_id}`);

    let recordPersonalInfoData = await db.querysql(ctx, `SELECT ${cupmstr}
    ,b.education lastEducation,b.religion faithReligion FROM loan_user_info a, loan_user b WHERE a.id= b.info_id AND b.id=${loan_order.user_id}`);
    if (recordPersonalInfoData && recordPersonalInfoData.length > 0) {
      let recordPersonalInfo = recordPersonalInfoData[0];
      if (recordPersonalInfo.birthday) {
        recordPersonalInfo.birthday = new Date(recordPersonalInfo.birthday).getTime();
      } else {
        recordPersonalInfo.birthday = new Date('1992-01-01').getTime();
      }
      if (!recordPersonalInfo.gender) {
        recordPersonalInfo.gender = 'MALE';
      }
      if (!recordPersonalInfo.marital_status) {
        recordPersonalInfo.marital_status = 'SINGLE';
      }
      if (!recordPersonalInfo.children_number) {
        recordPersonalInfo.children_number = 'ZERO';
      }
      if (!recordPersonalInfo.residenceDuration) {
        recordPersonalInfo.residenceDuration = 'THREE_MONTH ';
      }
      //let eduction = [{ name: "DIPLOMA_I", val: 1 }, { name: "DIPLOMA_II", val: 2 }, { name: "DIPLOMA_III", val: 3 }, { name: "SD", val: 4 }, { name: "SLTP", val: 5 }, { name: "SLTA", val: 6 }, { name: "S1", val: 7 }, { name: "S2", val: 8 }, { name: "S3", val: 9 }]
      //let religion = [{ name: "Islam", val: 1 }, { name: "Kekristenan", val: 2 }, { name: "Katolik", val: 3 }, { name: "Agama Hindu", val: 4 }, { name: "Agama Buddha", val: 5 }, { name: "Konfusianisme", val: 6 }]
     eductiondict.map(function(item, index, input){
        if(item.val==recordPersonalInfo.lastEducation){
          recordPersonalInfo.lastEducation=item.name
        }
     })

     religiondict.map(function(item, index, input){
      if(item.val==recordPersonalInfo.faithReligion){
        recordPersonalInfo.faithReligion=item.name
      }
   })

      res.recordPersonalInfo =  common.objKeySort(recordPersonalInfo);
      console.log(res.recordPersonalInfo)
      console.log('获取用户个人信息成功');
    } else {
      console.log('获取用户个人信息失败');
    }
    // 设备信息
    if (device_info) {
      let deviceInfo = {
        phoneRAM:'123123',
        phoneName:device_info.brand,
        phoneOverRAM:'123',
        modelNumber:device_info.phone_model,
        systemVersion:'Android 9.0',
        appVersion:'1.0',
        packageName:'com.lan.qu',
        appName:'lanqu',
        apps: device_info.app_list,
        uuid: device_info.uuid,
        imei: device_info.imei,
        brand: device_info.brand,
        model: device_info.phone_model,
        location: device_info.gps,
        ip: device_info.ip,
      };
      res.deviceInfo =  common.objKeySort(deviceInfo);
      console.log(res.deviceInfo)
      console.log('获取设备信息成功');
    } else {
      console.log('获取设备信息失败');
    }
    console.log(loan_order)
    console.log('获取订单信息成功');
  } else {
    console.log('获取订单信息失败');
  }

  // 获取产品appid和key
  let productdata = await db.queryone(ctx, 'products_product', 'appid,domain,`key`', { id: loan_order.product_id });
  if (productdata && productdata.appid && productdata.key && productdata.domain) {
    res.appId = productdata.appid;
    let postobj = common.signjsapi(res, productdata.key);
    let url = productdata.domain || 'http://market.test.janesi.cn';
    //let data = await common.webclient(url + '/loan/order_basic_info/', postobj, 'post',ctx);

    var options = {
      method: 'post',
      url: url + '/loan/order_basic_info/',
      json:postobj,
      headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
      }
  }
    let data = await koa2Req(options);

    console.log('提交贷款后返回：--------' + JSON.stringify(data.body));

    console.log(JSON.stringify(postobj));
    let datenow = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
    if (data && data.body.code == 0) {
      console.log('提交贷款成功，返回贷款编号：' + data.data);
      let strsql = `Update loan_order set updated_time= '${datenow}',push_date='${datenow}',pull_status=1,pid=${data.data} where order_no = '${id}'`;
      console.log(strsql);
      await ctx.db.query(strsql);

    } else {
      let strsql = `Update loan_order set updated_time= '${datenow}',push_date='${datenow}',pull_status=0,error_msg='${data.body.message}' where order_no = '${id}'`;
      console.log(strsql);
      await ctx.db.query(strsql);
      console.log('提交贷款失败，错误信息：' + data.body.message);
    }
  } else {
    console.log('获取产品失败');

  }
}

module.exports = router.routes()